<?php
/**
 * Created by JetBrains PhpStorm.
 * User: acumen
 * Date: 11/27/12
 * Time: 9:19 AM
 * To change this template use File | Settings | File Templates.
 */
if(!defined('BASEPATH')) exit('No direct script access allowed');

class VerifyLogin extends CI_Controller {
    function __construct() {
        parent::__construct();
        $this->load->model('user_model','',TRUE);
    }

    function index() {
        $this->load->library('form_validation');

        $this->form_validation->set_rules('username','Username','trim|required|xss_clear');
        $this->form_validation->set_rules('password','Password','trim|required|xss_clean||callback_check_database');

        if($this->form_validation->run() == FALSE) {
            $this->load->view('login_view');
        } else {
            // Go to private area
            redirect('home','refresh');
        }
    }

    function check_database($password) {
        $username = $this->input->post('username');
        // query database
        $result = $this->user_model->login($username,$password);
        if($result) {
            $sess_array = array();
            foreach($result as $row){
                $sess_array = array(
                    'username' => $row->username
                );
                $this->session->set_userdata('logged_in',$sess_array);
                session_start();
                $_SESSION['user_logged_in'] = $username;
            }
            setcookie('UserCookie',$username,time()+3600);
            return TRUE;
        } else {
            $this->form_validation->set_message('check_database','Invalid username or password');
            return false;
        }
    }
}
?>